import { store } from "@/store";
import { defineStore } from "pinia";
import UserProfileApi, {
  type EditUserPassowrdForm,
  type UserProfileListParams,
  type UserProfileType,
} from "@/api/user/profile";

export const useUserProfileStore = defineStore("user-profile", () => {
  const list = ref<UserProfileType[]>([]);

  const totalCount = ref(0);

  const totalPage = ref(0);

  const loading = reactive({
    list: false,
    create: false,
    update: false,
    delete: false,
    editPassword: false,
  });

  async function fetchUserProfileList(params: UserProfileListParams) {
    loading.list = true;
    const response = await UserProfileApi.getUserProfileList(params);
    loading.list = false;
    if (response) {
      list.value = response.records;
      totalCount.value = response.total_count;
      totalPage.value = response.total_page;
    }
  }

  async function fetchCreateUserProfile(data: Partial<UserProfileType>) {
    loading.create = true;
    await UserProfileApi.addUserProfile(data);
    loading.create = false;
  }

  async function fetchUpdateUserProfile(data: Partial<UserProfileType>) {
    loading.update = true;
    await UserProfileApi.updateUserProfile(data);
    loading.update = false;
  }

  async function fetchDeleteUserProfile(id: number) {
    loading.delete = true;
    await UserProfileApi.deleteUserProfile(id);
    loading.delete = false;
  }

  async function fetchEditUserPassowrd(data: EditUserPassowrdForm) {
    loading.editPassword = true;
    await UserProfileApi.editUserPassowrd(data);
    loading.editPassword = false;
  }

  return {
    list,
    totalCount,
    totalPage,
    loading,
    fetchUserProfileList,
    fetchCreateUserProfile,
    fetchUpdateUserProfile,
    fetchDeleteUserProfile,
    fetchEditUserPassowrd,
  };
});

export const useUserProfileStoreHook = () => {
  return useUserProfileStore(store);
};
